package cn.cocho.custom.yunCashierDf.phone.controller;

import cn.cocho.common.web.app.JsonResultContants;
import cn.cocho.common.web.utils.JsonUtils;
import cn.cocho.custom.yunCashierDf.common.controller.EncryptCode;
import cn.cocho.custom.yunCashierDf.common.controller.HttpSubmit;
import cn.cocho.custom.yunCashierDf.common.controller.QRCodeUtil;
import cn.cocho.custom.yunCashierDf.merchant.domain.MerchantInfo;
import cn.cocho.custom.yunCashierDf.merchant.domain.MerchantTransactionInfo;
import cn.cocho.custom.yunCashierDf.merchant.service.MerchantInfoService;
import cn.cocho.custom.yunCashierDf.merchant.service.MerchantTransactionInfoService;
import cn.cocho.custom.yunCashierDf.phone.service.PhoneService;
import cn.cocho.custom.yunCashierDf.uc.domain.UcUserInfo;
import cn.cocho.custom.yunCashierDf.utils.JsonResult;
import cn.cocho.custom.yunCashierDf.utils.Page;
import cn.cocho.custom.yunCashierDf.utils.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by lp on 2017-05-24.
 */
@Controller
public class PhoneController {
    @Autowired
    private PhoneService phoneService;

    @Autowired
    private MerchantInfoService merchantInfoService;

    @Autowired
    private MerchantTransactionInfoService merchantTransactionInfoService;
    //商户登入接口
    @ResponseBody
    @RequestMapping(value = "/anonymous/phone/userInfoLogin")
    public JsonResult userInfoLogin(UcUserInfo ucUserInfo) {
        return phoneService.userInfoLogin(ucUserInfo.getUsername(),ucUserInfo.getUserPassword());
    }
    //商户预订单列表接口
    @ResponseBody
    @RequestMapping(value = "/members/phone/orderNumberList")
    public JsonResult<Page<MerchantTransactionInfo>> orderNumberList(Page page, String order,String startTime,String endTime) throws ParseException{
        UcUserInfo userInfo=phoneService.getUserInfo();
        Date sTime=null;
        Date eTime=null;
       // System.out.println(startTime+"||"+endTime);
        if(startTime!=null&&endTime!=null&&!startTime.equals("")&&!endTime.equals("")){
            DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
           // Date myDate1 = dateFormat1.parse("2009-06-01");
            sTime=dateFormat1.parse(startTime);
            eTime=dateFormat1.parse(endTime);
        }
        return new JsonResult<Page<MerchantTransactionInfo>>(JsonResultContants.SUCCESS, "获取列表成功！", phoneService.getMerchantTransactionInfoList(page,userInfo.getUsername() ,order,sTime,eTime));
    }
    //商户预订单接口
    @ResponseBody
    @RequestMapping(value = "/members/phone/orderNum")
    public JsonResult<MerchantTransactionInfo> orderNum(String ordernum) {
        UcUserInfo userInfo=phoneService.getUserInfo();
        return new JsonResult<MerchantTransactionInfo>(JsonResultContants.SUCCESS, "获取成功！", phoneService.getMTInfo(ordernum, userInfo.getUsername()));
    }
    //预下单接口
    @ResponseBody
    @RequestMapping(value = "/members/phone/toPuat")
    public JsonResult toPuat(String chcdPara,String txamtPara,HttpServletRequest request) throws IOException {
        System.out.println("开始生产二维码！");
        UcUserInfo userInfo=phoneService.getUserInfo();
        System.out.println(userInfo.getMerchantId()+"wo shi id");
        MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(userInfo.getMerchantId());
        JsonResult result = null;
        if(merchantInfo != null){
            String backUrl = merchantInfo.getBackUrl();
            //支付类型
            String busicd = "PAUT";
            //编码格式
            String charset = merchantInfo.getCharset();
            //支付类型 ALP 支付宝
            String chcd = chcdPara;
            //机构号
            String inscd = merchantInfo.getInscd();
            //商户号
            String mchntid = merchantInfo.getMchntid();
            //订单号
            //String origOrderNum = String.valueOf(System.currentTimeMillis());  //订单号
            String origOrderNum = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            //签名方式
            String signType = merchantInfo.getSignType();
            //终端号
            String terminalid = userInfo.getUsername();
            //交易金额
            String txamt = txamtPara;  //钱数
            //交易方向
            String txndir = merchantInfo.getTxndir();
            //版本号
            String version = merchantInfo.getVersion();

            String newString = "backUrl="+backUrl+"&busicd="+busicd+"&charset="+charset+"&chcd="+chcd+"&inscd="+inscd+"&mchntid="+mchntid+"&orderNum="+origOrderNum+""
                               + "&signType="+signType+"&terminalid="+terminalid+"&txamt="+txamt+"&txndir="+txndir+"&version="+version+"";
            String newSign = newString + merchantInfo.getSignKey();
            String sign = new EncryptCode().SHA256(newSign);

            JSONObject jsonObj = new JSONObject();
            jsonObj.put("txndir", txndir);
            jsonObj.put("busicd", busicd);
            jsonObj.put("chcd", chcd);
            jsonObj.put("inscd", inscd);
            jsonObj.put("charset", charset);
            jsonObj.put("mchntid", mchntid);
            jsonObj.put("signType", signType);
            jsonObj.put("terminalid", terminalid);
            jsonObj.put("txamt", txamt);
            jsonObj.put("orderNum", origOrderNum);
            jsonObj.put("backUrl", backUrl);
            jsonObj.put("version", version);
            jsonObj.put("sign",sign );

            String jsonString = jsonObj.toString();
            System.out.println(jsonString);

            //获取返回值
            String returnValue = new HttpSubmit().postAttendanceInfo(jsonString, StringUtil.requestUrl);
            System.out.println(returnValue);
            //解析json数据
            JSONObject jsonObject = JSONObject.fromObject(returnValue);
            //生成二维码
            String qrcode = null;
            String localUrl = "";
            if(jsonObject.getString("respcd").equals("09")){
                qrcode = jsonObject.getString("qrcode");
                String local = request.getRealPath("/") + "/images";
                try {
                    localUrl = QRCodeUtil.encode(qrcode, local, origOrderNum ,true);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                MerchantTransactionInfo merchantTransactionInfo = new MerchantTransactionInfo();
                merchantTransactionInfo.setPaymentType(busicd);
                merchantTransactionInfo.setMerchantId(merchantInfo.getMerchantId());
                merchantTransactionInfo.setBusicd(busicd);
                int temp=(int)(Math.random()*100000);
                while(temp/10000<1){
                    temp=(int)(Math.random()*100000);
                }
                merchantTransactionInfo.setOrderNum(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + temp);
                merchantTransactionInfo.setOrigOrderNum(origOrderNum);
                merchantTransactionInfo.setChcd(chcd);
                merchantTransactionInfo.setRespcd(jsonObject.getString("respcd"));
                merchantTransactionInfo.setTxamt(txamt);
                merchantTransactionInfo.setSign(sign);
                merchantTransactionInfo.setQrcode(qrcode);
                merchantTransactionInfo.setTerminalid(terminalid);
                merchantTransactionInfo.setSearchStatus("0");
                merchantTransactionInfoService.insertMerchantTransactionInfo(merchantTransactionInfo);

                String QRcodeUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/yunCashierDf/images/" + localUrl;
                jsonObject.put("QRcodeUrl",QRcodeUrl);
            }
            result = new JsonResult(JsonResultContants.SUCCESS, "请求预下单接口成功", jsonObject);
        }else{
            JSONObject returnJson = new JSONObject();
            returnJson.put("errorDetail","请求预下单接口出错");
            result = new JsonResult(JsonResultContants.FAIL, "请求预下单接口失败", returnJson);
        }
        return result;
    }

    //H5支付接口　保存订单信息
    @ResponseBody
    @RequestMapping(value = "/anonymous/phone/toH5")
    public JsonResult toH5(MerchantTransactionInfo merchantTransactionInfo) throws IOException {
        JsonResult result;
        int temp=(int)(Math.random()*100000);
        while(temp/10000<1){
            temp=(int)(Math.random()*100000);
        }
        merchantTransactionInfo.setRespcd("H5");
        merchantTransactionInfo.setOrderNum(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + temp);
        merchantTransactionInfo.setSearchStatus("0");
        boolean insertResult = merchantTransactionInfoService.insertMerchantTransactionInfo(merchantTransactionInfo);
        if (insertResult == true) {
            result = new JsonResult(JsonResultContants.SUCCESS, "新增订单信息成功！", merchantTransactionInfo.getMerchantId());
        } else {
            result = new JsonResult(JsonResultContants.FAIL, "新增订单信息失败！");
        }
        return result;
    }
    //商户登入接口
    @ResponseBody
    @RequestMapping(value = "/anonymous/phone/getMerchantInfo")
    public JsonResult getMerchantInfo(String txamt,String ordernum) {
        JsonResult result;
        MerchantInfo merchantInfo=phoneService.getMerchanInfo(txamt, ordernum);
        if (merchantInfo != null) {
            result = new JsonResult<MerchantInfo>(JsonResultContants.SUCCESS, "获取商户信息成功！", merchantInfo);
        } else {
            result = new JsonResult<MerchantInfo>(JsonResultContants.FAIL, "无法获取商户信息！");
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/anonymous/phone/getMerchantInfoById", method = RequestMethod.POST)
    public JsonResult<MerchantInfo> getMerchantInfoById(String merchantId) {
        JsonResult<MerchantInfo> result;
        MerchantInfo merchantInfo = merchantInfoService.getMerchantInfoById(merchantId);
        if (merchantInfo != null) {
            result = new JsonResult<MerchantInfo>(JsonResultContants.SUCCESS, "获取商户信息成功！", merchantInfo);
        } else {
            result = new JsonResult<MerchantInfo>(JsonResultContants.FAIL, "无法获取商户信息！");
        }
        return result;
    }
}
